package org.example.skytool.es.doc;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.example.exception.EsException;
import org.example.skytool.commom.BeanUtils;
import org.example.skytool.json.JackSonUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

@Component
public class EsDocUtil {

    @Resource
    private RestHighLevelClient restHighLevelClient;



    public <T> T selectDocumentById(String name, String id, Class<T> clazz) {
        try {
            // 1.创建request对象
            GetRequest request = new GetRequest(name, id);
            // 2.发送请求，得到结果
            GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
            // 3.解析结果
            return parseResponse(response, clazz);
        } catch (Exception e) {
            throw new EsException(e.getMessage());
        }
    }

    private <T> T parseResponse(GetResponse response, Class<T> clazz) {
        Map<String, Object> map = response.getSource();
        return BeanUtils.mapToBean(clazz,map);
    }


    public String insertDocument(String id, String name, Object obj) {
        try {
            IndexRequest request = new IndexRequest(name).id(id);
            request.source(JackSonUtil.encode(obj), XContentType.JSON);
            IndexResponse reponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            return id;
        } catch (IOException e) {
            e.printStackTrace();
            throw new EsException(e.getMessage());
        }
    }

    public void updateDocument(String id, String name, String doc) {
        try {
            UpdateRequest request = new UpdateRequest(name, id);
            request.doc(doc, XContentType.JSON);
            restHighLevelClient.update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new EsException(e.getMessage());
        }
    }

    public void deleteDocument(String id, String name) {
        try {
            DeleteRequest request = new DeleteRequest(name, id);
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new EsException(e.getMessage());
        }
    }


}
